from loguru import logger
from django.shortcuts import render
from django.core.files.storage import default_storage
from django.db.models import Case, When, Value, CharField
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.conf import settings
from django.views import View
from django.http import FileResponse, Http404

from django.http import JsonResponse
from apps.products.models.products import Products, ProductType
from apps.products.serializers.serializers import ProductTypeSerializer

# 基础依赖
from rest_framework.generics import ListAPIView
from django.db.models import Q

# 如果使用 Django 原生权限系统
from rest_framework.permissions import IsAuthenticated

# # 序列化器导入（根据实际项目结构调整路径）
# from .serializers import ProductTypeSerializer  # 产品类型序列化器
# from accounts.serializers import UserSimpleSerializer  # 用户简单信息序列化器


from django.contrib.auth import authenticate, login


# Create your views here.


@login_required(login_url=settings.LOGIN_URL)
def index(request):
    return render(request, "products/home.html")


def get_user_products(request):
    products = {
        "has_next": True,
        "current_page": 1,
        "total_pages": 5,
        "has_previous": False,
        "products": [
            {
                "id": i,
                "name": f"Product_0{i}",
                "description": "TEST PRODUCT",
                "create_time": "2015/05/01",
                "logo": "/static/products/images/default-logo.jpg",
            }
            for i in range(1, 20)
        ],
    }

    return JsonResponse(products)


def get_user_products_selector(request):
    products = [{"id": "001", "name": "test"}]
    return JsonResponse(
        {"products": products, "default_product": "Android App Demo"}  # 当前选中产品
    )


from django.core.paginator import Paginator


@method_decorator(login_required, name="dispatch")
class UserProductsView(View):
    # 每页个数
    items_per_page = 8

    def get(self, request):
        page = request.GET.get("page", 1)
        logger.info(f"query {request.user} products")
        products = (
            Products.objects.select_related("creator")
            .prefetch_related("managed_users")
            .filter(Q(creator=request.user) | Q(administrators=request.user))
            .order_by("create_time")
            .all()
        )
        logger.debug("select products sql >>>\n{} ", products.query)
        paginator = Paginator(products, self.items_per_page)
        page_obj = paginator.get_page(page)
        return JsonResponse(
            {
                "products": list(
                    page_obj.object_list.values(
                        "id", "name", "description", "create_time", "logo"
                    )
                ),
                "has_previous": page_obj.has_previous(),
                "has_next": page_obj.has_next(),
                "current_page": page_obj.number,
                "total_pages": paginator.num_pages,
            }
        )

    def post(self, request):
        try:
            # 获取表单数据
            name = request.POST.get("name")
            description = request.POST.get("description")
            logo = request.FILES.get("logo")

            # 基础验证
            if not name:
                return JsonResponse(
                    {"status": "error", "message": "产品名称不能为空"}, status=400
                )

            # 保存文件
            if logo:
                logo_path = default_storage.save(f"products/logo/{logo.name}", logo)
            else:
                logo_path = None

            # 创建产品
            Products.objects.create(
                creator=request.user, name=name, description=description, logo=logo_path
            )

            return JsonResponse({"status": "success", "message": "产品创建成功"})

        except Exception as e:
            return JsonResponse(
                {"status": "error", "message": f"服务器错误: {str(e)}"}, status=500
            )


class ProductView(View):
    def get(self, request, id):
        product = (
            Products.objects.select_related("creator")
            .prefetch_related("managed_users")
            .filter(id=id)
            .first()
        )
        if not product:
            return JsonResponse({"status": "error", "message": "产品不存在"}, status=404)
        return JsonResponse(
            {
                "id": product.id,
                "name": product.name,
                "description": product.description,
                "create_time": product.create_time,
                "logo": f"{settings.MEDIA_URL}{product.logo}" if product.logo else None,
                "creator": {
                    "id": product.creator.id,
                    "username": product.creator.username,
                },
                "managed_users": list(product.managed_users.values("id", "username")),
            }
        )


@method_decorator(login_required, name="dispatch")
class UserProductsSelectorView(View):
    def get(self, request):
        products = [{"id": "001", "name": "test"}]
        return JsonResponse(
            {"products": products, "default_product": "Android App Demo"}  # 当前选中产品
        )


# 产品分类接口
class ProductTypeAPI(ListAPIView):
    """产品分类"""

    queryset = ProductType.objects.filter()
    serializer_class = ProductTypeSerializer


@method_decorator(login_required, name="dispatch")
class ProductLogo(View):
    """获取产品logo"""

    # 映射 Content-Type
    content_type_map = {
        ".jpg": "image/jpeg",
        ".jpeg": "image/jpeg",
        ".png": "image/png",
        ".svg": "image/svg+xml",
    }

    def get(self, request, year, month, day, name):
        logger.debug("get product logo {}", request.path)
        # 图片路径
        file = settings.MEDIA_ROOT.joinpath("products", "logo", year, month, day, name)
        if not file.exists() and not file.is_file():
            raise Http404("图片文件不存在")
        # 获取文件扩展名
        ext = file.suffix
        content_type = self.content_type_map.get(ext, "application/octet-stream")

        # 返回图片响应
        return FileResponse(
            open(file, "rb"),
            content_type=content_type,  # 根据实际格式调整
            as_attachment=False,  # True 会触发下载
        )


class ProductTypeAPIView(View):
    def get(self, request):
        types = ProductType.objects.annotate(
            category_display=Case(
                When(category="APP", then=Value("移动应用")),
                When(category="WEB", then=Value("网页应用")),
                When(category="API", then=Value("接口服务")),
                output_field=CharField(),
            )
        ).values("id", "name", "category_display")
        return JsonResponse(list(types), safe=False)
